import * as THREE from "three";
import * as Cesium from "cesium";

export let viewer, threeScene, threeCamera, threeRenderer, texture
export function initCesium(divId) {
  const tianditutkArr = [
    "590447cdbdf97775b57588a69ebb903d",
    "75f1cc913e8d68f7bd4b6f6383f78ceb",
    "4c4c0f03b0bdb58811f657fec0c09eb5",
  ];
  // ['590447cdbdf97775b57588a69ebb903d', '75f1cc913e8d68f7bd4b6f6383f78ceb', '4c4c0f03b0bdb58811f657fec0c09eb5',
  // '67cd2f398449d93fcd47a54e1ea620e3']
  const tianditutk =
    tianditutkArr[Math.floor(Math.random() * tianditutkArr.length)];
  // 设置Cesium静态资源路径
  let key =
    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJhZjE5ZTBhZC00YzE1LTQyMWYtOWM4MC00NmFlZjZhOGI3ZDciLCJpZCI6MTI4NTI2LCJpYXQiOjE2OTg4MzczOTN9.26EHXec7Ufty_B4e5_YWcB0t--zlquly7r66WVSS9wE";
  Cesium.Ion.defaultAccessToken = key;
  // 设置Cesium默认视角
  Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(
    108.4,
    21.3,
    129.3,
    48.6
  );

  // 创建Cesium Viewer
  viewer = new Cesium.Viewer(divId, {
    infoBox: false,
    selectionIndicator: false,
    homeButton: false,
    sceneModePicker: false,
    navigationHelpButton: false,
    navigationInstructionsInitiallyVisible: false,
    animation: false,
    timeline: false,
    fullscreenButton: false,
    allowTextureFilterAnisotropic: false,
    baseLayerPicker: false,
    contextOptions: {
      requestWebgl2: true,
      // 默认开启webgl2
      requestWebgl1: false,
      webgl: {
        alpha: false,
        antialias: true,
        preserveDrawingBuffer: true,
        failIfMajorPerformanceCaveat: false,
        depth: true,
        stencil: false,
        anialias: false,
      },
    },
    targetFrameRate: 60,
    resolutionScale: 0.1,
    orderIndependentTranslucency: true,
    //加载底图
    baseLayer: new Cesium.ImageryLayer(
      new Cesium.WebMapTileServiceImageryProvider({
        url:
          "http://t0.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=" +
          tianditutk,
        layer: "tdtImgLayer",
        style: "default",
        format: "image/jpeg",
        tileMatrixSetID: "GoogleMapsCompatible", //使用谷歌的瓦片切片方式
        show: true,
      })
    ),
    // 开启2.5D视角
    // sceneMode: Cesium.SceneMode.COLUMBUS_VIEW,
    geocoder: false,
    automaticallyTrackDataSourceClocks: false,
    dataSources: null,
    clock: null,
    // 添加地形
    terrain: Cesium.Terrain.fromWorldTerrain(),
    terrainShadows: Cesium.ShadowMode.ENABLED,
    // 添加天空盒
    // skyBox: new Cesium.SkyBox({
    //   sources: {
    //     positiveX: 'park/posx.jpg',
    //     negativeX: 'park/negx.jpg',
    //     positiveY: 'park/posx.jpg',
    //     negativeY: 'park/negx.jpg',
    //     positiveZ: 'park/posy.jpg',
    //     negativeZ: 'park/negy.jpg'
    //   }
    // })
  });
}
export function initThree(divId) {
  // 获取cesium的canvas
  const canvas = viewer.scene.canvas;
  // canvas.style.visibility = 'hidden';
  // canvas.style.opacity = 0;

  // 创建three.js的canvas纹理
  texture = new THREE.CanvasTexture(canvas);
  texture.minFilter = THREE.LinearFilter;
  texture.magFilter = THREE.LinearFilter;
  texture.wrapS = THREE.ClampToEdgeWrapping;
  texture.wrapT = THREE.ClampToEdgeWrapping;
  texture.colorSpace = THREE.SRGBColorSpace;

  // 初始化Three.js
  threeScene = new THREE.Scene();
  // threeScene.background = texture;
  // 创建Three.js相机
  threeCamera = new THREE.PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    1,
    100000000
  );
  // 创建Three.js渲染器
  threeRenderer = new THREE.WebGLRenderer({
    alpha: true,
    antialias: true,
    logarithmicDepthBuffer: true,
  });
  // 设置Three.js渲染器的大小
  threeRenderer.setSize(window.innerWidth, window.innerHeight);
  // 将Three.js渲染器添加到Cesium Viewer的canvas中
  document
    .querySelector(divId)
    .appendChild(threeRenderer.domElement);
  threeRenderer.domElement.style.position = "absolute";
  threeRenderer.domElement.style.top = "0";
  threeRenderer.domElement.style.left = "0";
  threeRenderer.domElement.style.pointerEvents = "none";

  // 创建不可见的地球球体
  const earthRadius = 6378137;
  const earthGeometry = new THREE.SphereGeometry(earthRadius, 64, 64);
  const earthMaterial = new THREE.MeshBasicMaterial({
    color: 0xffffff,
    colorWrite: false,
  });
  const earthMesh = new THREE.Mesh(earthGeometry, earthMaterial);
  threeScene.add(earthMesh);
  // 设置相机位置
  // threeCamera.position.set(0, 0, 100);
}
// 设置请求动画帧函数
export function animate() {
  texture.needsUpdate = true;
  updateThreeCamera();
  requestAnimationFrame(animate);
  threeRenderer.render(threeScene, threeCamera);
}

export function updateThreeCamera() {
  // 将three的相机的视野角度与cesium的相机的视野角度保持一致
  threeCamera.fov = Cesium.Math.toDegrees(viewer.camera.frustum.fovy);
  // 更新相机的投影矩阵
  threeCamera.updateProjectionMatrix();

  // 更新相机位置和旋转矩阵
  threeCamera.matrixAutoUpdate = false; // 禁止自动更新矩阵
  let cvm = viewer.camera.viewMatrix;
  let civm = viewer.camera.inverseViewMatrix;

  // 设置相机的位置
  threeCamera.position.set(civm[12], civm[13], civm[14]);
  threeCamera.lookAt(0, 0, 0);

  // 设置相机矩阵
  threeCamera.matrixWorld.set(
    civm[0],
    civm[4],
    civm[8],
    civm[12],
    civm[1],
    civm[5],
    civm[9],
    civm[13],
    civm[2],
    civm[6],
    civm[10],
    civm[14],
    civm[3],
    civm[7],
    civm[11],
    civm[15]
  );

  // 相机的逆矩阵
  threeCamera.matrixWorldInverse.set(
    cvm[0],
    cvm[4],
    cvm[8],
    cvm[12],
    cvm[1],
    cvm[5],
    cvm[9],
    cvm[13],
    cvm[2],
    cvm[6],
    cvm[10],
    cvm[14],
    cvm[3],
    cvm[7],
    cvm[11],
    cvm[15]
  );
}

export function setModel(
  model,
  longitude,
  latitude,
  height,
  heading = 0,
  pitch = 0,
  roll = 0
) {
  //  模型所在位置
  let position = Cesium.Cartesian3.fromDegrees(longitude, latitude, height);

  // 模型的方向
  let hpr = new Cesium.HeadingPitchRoll(
    Cesium.Math.toRadians(heading),
    Cesium.Math.toRadians(pitch),
    Cesium.Math.toRadians(roll)
  );

  // 模型的矩阵
  const modelMatrix = Cesium.Transforms.headingPitchRollToFixedFrame(
    position,
    hpr
  );

  // 将cesium的矩阵转为three的矩阵
  const threeMatrix = new THREE.Matrix4();

  threeMatrix.fromArray([
    modelMatrix[0],
    modelMatrix[1],
    modelMatrix[2],
    modelMatrix[3],
    modelMatrix[4],
    modelMatrix[5],
    modelMatrix[6],
    modelMatrix[7],
    modelMatrix[8],
    modelMatrix[9],
    modelMatrix[10],
    modelMatrix[11],
    modelMatrix[12],
    modelMatrix[13],
    modelMatrix[14],
    modelMatrix[15],
  ]);

  // 调整坐标系对齐
  // 绕x轴旋转90度
  const rotationX = new THREE.Matrix4().makeRotationX(Math.PI / 2);
  // 绕y轴旋转90度
  const rotationY = new THREE.Matrix4().makeRotationY(Math.PI / 2);

  // 将两个矩阵相乘
  threeMatrix.multiply(rotationX).multiply(rotationY);

  // 将变换后的矩阵应用到模型里
  model.matrix.copy(threeMatrix);
  model.matrix.decompose(model.position, model.quaternion, model.scale);
  model.updateMatrixWorld();
  return model;
}
